<script setup>
import QrCodeVue from 'qrcode.vue';
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

// 记录当前要接收消息的对象，使用唯一值,这个看自己，可以使用 ip 等，这里只是演示就写死数据
const selfInfo = '1';

const socketInstance = ref();

const isCoding = ref(false);

const router = useRouter();

onMounted(() => {
    if (window.WebSocket) {
        socketInstance.value = new WebSocket(`ws://localhost:5269/login/${selfInfo}`);

        socketInstance.value.onmessage = (message) => {
            console.log('message', message);
            const { data } = JSON.parse(message.data);
            if (data.isCode !== void 0) isCoding.value = data.isCode;
            // 有 token 表示登录成功
            if (data.token) router.replace('/result')
        }
    }
})

</script>

<template>
    <div class="container">
        <div class="box">
            <QrCodeVue size="200" :value="JSON.stringify({ code: selfInfo })"></QrCodeVue>
            <div v-if="isCoding" class="mask">
                已检测到扫码
            </div>
        </div>
    </div>
</template>

<style scoped>
.container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 500px;
}

.box {
    width: 200px;
    height: 200px;
    position: relative;
}

.mask {
    position: absolute;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, .9);
    color: white;
    display: flex;
    justify-content: center;
    align-items: center;
    top: 0;
}
</style>